﻿using System;
using System.Configuration;
using System.Reflection;

namespace Grebok.Persistence
{
    /// <summary>
    /// Summary description for DataAccessProviderFactory.
    /// </summary>
    public sealed class DataAccessProviderFactory : IDataProviderFactory
    {
        private static Assembly activeProvider = null;
        private static IDataProviderFactory activeDataProviderFactory = null;

        DataAccessProviderFactory()
        {
            string providerName = ConfigurationManager.AppSettings["DataProvider"];
            string providerFactoryName = ConfigurationManager.AppSettings["DataProviderFactory"];
            activeProvider = Assembly.Load(providerName);
            activeDataProviderFactory = (IDataProviderFactory)activeProvider.CreateInstance(providerFactoryName);
        }

        /// <summary>
        /// Return the Singleton Instance of DataAccessProviderFactory.
        /// </summary>
        public static DataAccessProviderFactory Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        /// <summary>
        /// Get Data Context from active data provider factory.
        /// </summary>
        /// <returns></returns>
        public IDataContext GetDataContext()
        {
            return activeDataProviderFactory.GetDataContext();
        }

        /// <summary>
        /// Nested helper class
        /// </summary>
        class Nested
        {
            static Nested()
            {
            }

            internal static readonly DataAccessProviderFactory instance = new DataAccessProviderFactory();
        }
    }
}
